﻿using System;
using System.Linq;
using System.Web;
using CoolCode.Reflection;

namespace CoolCode.Web
{
    public class Utility
    {
        /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strPath">指定的路径</param>
        /// <returns>绝对路径</returns>
        public static string GetMapPath(string strPath)
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Server.MapPath(strPath);
            }
            else //非web程序引用
            {
                strPath = strPath.Replace("/", "\\");
                if (strPath.StartsWith("\\"))
                {
                    strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');
                }
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
            }
        }

        /// <summary>
        /// URL Encode
        /// </summary>
        /// <param name="str">String</param>
        /// <returns></returns>
        public static string UrlEncode(string str)
        {
            return HttpUtility.UrlEncode(str);
        }

        /// <summary>
        /// URL Decode
        /// </summary>
        /// <param name="str">String</param>
        /// <returns></returns>
        public static string UrlDecode(string str)
        {
            return HttpUtility.UrlDecode(str);
        }

        /// <summary>
        /// DateTime Encode
        /// </summary>
        /// <param name="dt">Date Time</param>
        /// <returns></returns>
        public static string UrlEncode(DateTime dt)
        {
            return HttpUtility.UrlEncode(DateFormat.ToSqlDateTime(dt));
        }

        public static string UrlEncode(object obj)
        {
            if (obj == null)
                return string.Empty;
            else if (obj is DateTime)
                return UrlEncode((DateTime)obj);
            return HttpUtility.UrlEncode(obj.ToString());
        }

        /// <summary>
        /// 返回 HTML 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>编码结果</returns>
        public static string HtmlEncode(string str)
        {
            return HttpUtility.HtmlEncode(str);
        }

        /// <summary>
        /// 返回 HTML 字符串的解码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string HtmlDecode(string str)
        {
            return HttpUtility.HtmlDecode(str);
        }

        /// <summary>
        /// 为脚本替换特殊字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToScript(string str)
        {
            str = str.Replace("\\", "\\\\");
            str = str.Replace("'", "\\'");
            str = str.Replace("\"", "\\\"");
            return str;
        }

        /// <summary>
        /// 替换回车换行符为html换行符
        /// </summary>
        public static string FormatString(string str)
        {
            if (str == null)
            {
                return string.Empty;
            }
            else
            {
                str = str.Replace("\r\n", "<br/>");
                str = str.Replace("\n", "<br/>");
            }
            return str;
        }

        public static string FormatDecimal(string str, int decimalSpace)
        {
            int dotInd = str.IndexOf(".");
            if (dotInd > 0)
            {
                for (int i = str.Length - dotInd - 1; i < decimalSpace; i++)
                    str += "0";
            }
            else
            {
                str += ".";
                for (int i = 0; i < decimalSpace; i++)
                    str += "0";
            }
            return str;
        }

        public static string ToQueryString<T>(T model) //where T : class, new()
        {
            string qs = string.Empty;
            if (model != null)
            {
                var kv = BLReflection.ToDictionary<T>(model);
                var en = kv.GetEnumerator();
                while (en.MoveNext())
                {
                    qs += en.Current.Key + "=" + Utility.UrlEncode(en.Current.Value) + "&";
                }
                if (qs.EndsWith("&"))
                    qs = qs.Remove(qs.Length - 1);
            }
            return qs;
        }


        /// <summary>
        /// If application path is "/Inquiry" and current page path is "/Inquiry/Views/SO902.aspx",
        /// return "../"
        /// </summary>
        /// <returns></returns>
        public static string GetRelativePath()
        {
            string root = HttpContext.Current.Request.ApplicationPath.ToLower();
            string currPath = HttpContext.Current.Request.Path.ToLower();
            if (!root.StartsWith("/")) root = "/" + root;
            if (!currPath.StartsWith("/")) currPath = "/" + currPath;

            int rootIndex = currPath.IndexOf(root);
            currPath = currPath.Substring(root.Length);
            if (currPath.Length > 0)
                if (currPath[0] == '/')
                    currPath = currPath.Substring(1);
            if (!currPath.Contains('/'))
                return string.Empty;//page in root
            string[] s = currPath.Split('/');
            if (s != null && s.Length > 0)
            {
                string result = "";
                for (int i = 0; i < s.Length - 1; i++)
                    result += "../";
                return result;
            }
            return string.Empty;
        }
    }
}
